package com.hnzq.cloud.freshsendmessage.consumer;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnzq.cloud.OrderAPI;
import com.hnzq.cloud.dto.OrderDto;
import com.hnzq.cloud.param.UpdateOrderStatusParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
@RocketMQMessageListener(topic = "order_topic",
        consumerGroup = "orderCancel_group",
        messageModel = MessageModel.BROADCASTING)
@Slf4j
public class OrderCancelConsumer implements RocketMQListener<Integer> {

    @Autowired
    private OrderAPI orderAPI;

    ObjectMapper mapper = new ObjectMapper();

    /**
     * 订单是否取消
     * @param orderId
     */
    @SneakyThrows
    @Override
    public void onMessage(Integer orderId) {
        log.info("收到订单消息：{}",orderId);
        //根据id得到对象
        OrderDto orderDto = mapper.convertValue(orderAPI.findOrderByOrderId(orderId).getData()
                , new TypeReference<OrderDto>() {});

        if (orderDto==null){
            log.info("没有该订单：{}",orderId);
        }else {
            if (orderDto.getOrderStatus() == 0){
//                UpdateOrderStatusParam updateOrderStatusParam = new UpdateOrderStatusParam();
//                updateOrderStatusParam.setOrderId(orderId);
//                updateOrderStatusParam.setOrderStatus(-1);
//                orderAPI.updateOrderStatus(updateOrderStatusParam);
                log.info("订单已经取消，订单号为：{}",orderId);
            }else if (orderDto.getOrderStatus() == 1){
                log.info("已支付，下单成功，订单号为：{}",orderId);
            }else if (orderDto.getOrderStatus() == -1){
                log.info("订单已提前取消，订单号为：{}",orderId);
            }
            else {
                log.info("订单已支付过，请检查订单的状态：{}",orderDto.getOrderStatus());
            }
        }
    }
}
